package com.ruoyi.common.redis.service;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.utils.DateUtils;
import org.apache.poi.ss.usermodel.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

/**
 * spring redis 工具类
 * 
 * @author ruoyi
 **/
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisService
{
    private static Logger log = LoggerFactory.getLogger(RedisService.class);
    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;
    private final static String SEND_SMS_KEY = CacheConstants.SEND_SMS_KEY;
    private final static String User_Money_Key=CacheConstants.USER_MONEY_KEY;
    private final static String SYS_CONFIG = CacheConstants.SYS_CONFIG;
    private final static String WITHDRAWAL_AMOUNT_DAY=CacheConstants.WITHDRAWAL_AMOUNT_DAY;
    private final static String GROUP_KEY=CacheConstants.GROUP_KEY;
    private final static String GROUP_STATUS_KEY=CacheConstants.GROUP_STATUS_KEY;
    private final static String GROUP_COUNT_KEY=CacheConstants.GROUP_COUNT_KEY;
    private final static String GENERAL_LEDGER=CacheConstants.GENERAL_LEDGER;
    private final static String GROUP_PRICE_KEY=CacheConstants.GROUP_PRICE_KEY;
    private final static String GROUP_PRICE_REDPACK=CacheConstants.GROUP_PRICE_REDPACK;
    private final static String GROUP_PRICE_TotalValue=CacheConstants.GROUP_PRICE_TotalValue;
    private final static String HANG_UP_KEY=CacheConstants.HANG_UP_KEY;
    private final static String BUY_KEY=CacheConstants.BUY_KEY;
    private final static String BILL_DETAIL_KEY=CacheConstants.BILL_DETAIL_KEY;
    private final static String TeamAssess_KEY=CacheConstants.TeamAssess_KEY;
    private final static String WITHDRAWN_DAY_KEY=CacheConstants.WITHDRAWN_DAY_KEY;
    private final static String RESERVE_ASSETS_MONTH=CacheConstants.RESERVE_ASSETS_MONTH;
    private final static String RESERVED_ACTIVITY_KEY=CacheConstants.RESERVED_ACTIVITY_KEY;
    private final static String Register_Price_Key=CacheConstants.Register_Price_Key;
    @Autowired
    public RedisTemplate redisTemplate;


    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final String key, final T value)
    {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     * @param timeout 时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Long timeout, final TimeUnit timeUnit)
    {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(final String key, final long timeout)
    {
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @param unit 时间单位
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit)
    {
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 获取有效时间
     *
     * @param key Redis键
     * @return 有效时间
     */
    public long getExpire(final String key)
    {
        return redisTemplate.getExpire(key);
    }

    /**
     * 判断 key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public Boolean hasKey(String key)
    {
        return redisTemplate.hasKey(key);
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key)
    {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 删除单个对象
     *
     * @param key
     */
    public boolean deleteObject(final String key)
    {
        return redisTemplate.delete(key);
    }

    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return
     */
    public long deleteObject(final Collection collection)
    {
        return redisTemplate.delete(collection);
    }

    /**
     * 缓存List数据
     *
     * @param key 缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> long setCacheList(final String key, final List<T> dataList)
    {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getCacheList(final String key)
    {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    /**
     * 缓存Set
     *
     * @param key 缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet)
    {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        Iterator<T> it = dataSet.iterator();
        while (it.hasNext())
        {
            setOperation.add(it.next());
        }
        return setOperation;
    }

    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
    public <T> Set<T> getCacheSet(final String key)
    {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     */
    public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
    {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    /**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */
    public <T> Map<String, T> getCacheMap(final String key)
    {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 往Hash中存入数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @param value 值
     */
    public <T> void setCacheMapValue(final String key, final String hKey, final T value)
    {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 获取Hash中的数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public <T> T getCacheMapValue(final String key, final String hKey)
    {
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys)
    {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 获得缓存的基本对象列表
     * 
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(final String pattern)
    {
        return redisTemplate.keys(pattern);
    }
    /**
     * 将用户每日拼团信息写入缓存
     */
    public static void setGroupCaChe(RedisService redisService,Long userId,Map<String,Object> map){
        String key=getGroupStatusKey(userId);
        redisService.setCacheObject(key,map, DateUtils.getLastSeconds(), TimeUnit.SECONDS);
    }
    /**
     * 将用户每日拼团信息写入缓存
     */
    public static Map<String,Object> getGroupCaChe(RedisService redisService,Long userId){
        String key=getGroupStatusKey(userId);
        if(redisService.hasKey(key)){
            return redisService.getCacheObject(key);
        }
        return null;
    }

    /**
     * 累计拼团基金写入缓存
     * @param userId
     * @param newGroupPrice
     */
    public void setGroupPriceCache(RedisService redisService,Long userId, BigDecimal newGroupPrice) {
        String key=getGroupPriceKey(userId);
        redisService.setCacheObject(key,newGroupPrice, CacheConstants.GROUPPRICE_TIME_CACHE, TimeUnit.SECONDS);
    }
    /**
     * 读取累计拼团基金缓存
     * @param userId
     */
    public BigDecimal getGroupPriceCache(RedisService redisService,Long userId) {
        String key=getGroupPriceKey(userId);
        if(redisService.hasKey(key)){
            return redisService.getCacheObject(key);
        }
        return null;
    }
    /**
     * 写入拼团基金红包
     * 1.app显示拼团基金红包
     * 2.点击拼团基金红包，立马将待释放的拼团基金红包释放到拼团基金
     * 3.未点击拼团基金红包，则指定时间统一开拼团基金红包，释放到拼团基金
     * @param redisService
     * @param userId 用户id
     * @param price 金额
     */
    public static void setGroupRedPackCache(RedisService redisService,Long userId,BigDecimal price){
        String key = getGroupPriceRedPackKey(userId);
        redisService.setCacheObject(key,price);
    }
    /**
     * 读取拼团基金红包
     * 1.app显示拼团基金红包
     * 2.点击拼团基金红包，立马将待释放的拼团基金红包释放到拼团基金
     * 3.未点击拼团基金红包，则指定时间统一开拼团基金红包，释放到拼团基金
     * @param redisService
     * @param userId 用户id
     */
    public static BigDecimal getGroupRedPackCache(RedisService redisService,Long userId){
        String key = getGroupPriceRedPackKey(userId);
        if(redisService.hasKey(key)){
            return redisService.getCacheObject(key);
        }
        return null;
    }
    /**
     * 写入拼团基金待释放到释放数量
     * @param redisService
     * @param userId 用户id
     * @param map 总产值，每日已释放
     */
    public static void setGroupPriceTotalValueKey(RedisService redisService,Long userId,Map<String,Object> map){
        String key = getGroupPriceTotalValueKey(userId);
        redisService.setCacheObject(key,map);
    }

    /**
     * 读取拼团基金待释放到释放数量
     * @param redisService
     * @param userId 用户id
     */
    public static Map<String,Object> getGroupPriceTotalValueKey(RedisService redisService,Long userId){
        String key = getGroupPriceTotalValueKey(userId);
        if(redisService.hasKey(key)){
            return redisService.getCacheObject(key);
        }
        return null;
    }

    /**
     * 获取登录的key
     * @param token
     * @return
     */
    public static String getTokenKey(String token)
    {
        return ACCESS_TOKEN + token;
    }
    /**
     * redis短信验证码key
     * @param phone
     * @return
     */
    public static String getSmsKey(String phone)
    {
        return SEND_SMS_KEY + phone;
    }
    /**
     * 获取系统配置的key
     * @return
     */
    public static String getSysConfigKey()
    {
        return SYS_CONFIG;
    }
    /**
     * 玩家资金的key
     * @param customerId 客户id
     * @return
     */
    public static String getUserMoneyKey(Long customerId)
    {
        return User_Money_Key + customerId;
    }
    /**
     * 团队考核的key
     * @param customerId 客户id
     * @return
     */
    public static String getTeamAssessKey(Long customerId)
    {
        return TeamAssess_KEY + customerId;
    }
    /**
     * ftc挂卖的key
     * @param customerId 客户id
     * @return
     */
    public static String getHangUpKey(Long customerId)
    {
        return HANG_UP_KEY + customerId;
    }
    /**
     * 每日vc兑换额度的key
     * @param customerId 客户id
     * @return
     */
    public static String getWithdrawnDayKey(Long customerId)
    {
        return WITHDRAWN_DAY_KEY + customerId;
    }
    /**
     * 每月预留资产信息的key
     * @param customerId 客户id
     * @return
     */
    public static String getReserveAssetsMonthKey(Long customerId)
    {
        return RESERVE_ASSETS_MONTH + customerId;
    }
    /**
     * ftc求购的key
     * @param customerId 客户id
     * @return
     */
    public static String getBuyKey(Long customerId)
    {
        return BUY_KEY + customerId;
    }
    /**
     * 总账的key
     * @return
     */
    public static String getGeneralLedgerKey()
    {
        return GENERAL_LEDGER ;
    }

    /**
     * 获取每日提现额度的key
     * @param customerId 客户id
     * @return
     */
    public static String getWithdrawalAmountDayKey(Long customerId)
    {
        return WITHDRAWAL_AMOUNT_DAY + customerId;
    }

    /**
     * 获取拼团的key
     * @param customerId 客户id
     * @return
     */
    public static String getGroupKey(Long customerId)
    {
        return GROUP_KEY+customerId;
    }

    public static String getRegisterPriceKey(Long customerId){
        return Register_Price_Key+customerId;
    }
    /**
     * 拼团状态的key
     * @param customerId
     * @return
     */
    public static String getGroupStatusKey(Long customerId){
        return GROUP_STATUS_KEY+customerId;
    }

    /**
     * 累计拼团基金的key
     * @param customerId
     * @return
     */
    public static String getGroupPriceKey(Long customerId){
        return GROUP_PRICE_KEY+customerId;
    }
    public static String getBillDetailKey(Long customerId){
        return BILL_DETAIL_KEY+customerId;
    }
    /**
     * 拼团计数的key
     * @param groupId
     * @return
     */
    public static String getGroupCountKey(Long groupId){
        return GROUP_COUNT_KEY+groupId;
    }

    /**
     * 拼团基金红包的key
     * @param userId
     * @return
     */
    public static String getGroupPriceRedPackKey(Long userId){
        return GROUP_PRICE_REDPACK+userId;
    }
    /**
     * 拼团基金待释放到总产值的key
     * @param userId
     * @return
     */
    public static String getGroupPriceTotalValueKey(Long userId){
        return GROUP_PRICE_TotalValue+userId;
    }

    /**
     * 预留兑换活动VC每日限额的key
     * @param userId
     * @return
     */
    public static String getReservedActivityKey(Long userId) {
        return RESERVED_ACTIVITY_KEY+userId;
    }
    /**
     * 通过key前缀获取所有匹配的key的值
     * @param cardId
     */
    public Set<String> getRedis(String cardId) {
        // 获取所有的key
        Set<String> keys = redisTemplate.keys(cardId+"*");
        return keys;
    }

    /**
     * redis互斥锁
     * 标记是否插入
     * 已存在key，则返回false
     * 不存在，则插入一条记录，返回true
     * @return
     */
    public Boolean setIfAbsent(){
        return redisTemplate.opsForValue().setIfAbsent("SoulSynTask", new Date().getTime());
    }

    /**
     * 清除互斥锁
     */
    public void delSetIfAbsentKey(){
        redisTemplate.delete("SoulSynTask");
    }
    /**
     * 执行的方法（入口）
     * 定时自动开奖（未开红包），未开奖的用户自动开奖(凌晨之前)
     * 增加资产、明细记录
     */
    public void execute(Consumer consumer) {
        Boolean aBoolean =setIfAbsent();
        log.info("执行定时任务{}：{}",consumer.getClass().getName(),aBoolean);
        if (aBoolean) {
            try {
                log.info("SoulSynTask => 开始执行 ", Thread.currentThread().getName());
                consumer.accept(null);
                log.info("SoulSynTask => 执行完毕 ", Thread.currentThread().getName());
            }catch (Exception ex){
                log.error("定时任务异常，{}",aBoolean);
                log.error(ex.getMessage(),ex);
            }finally {
                delSetIfAbsentKey();
            }
        }else{
            log.info("执行定时任务,根据redis配置，不用执行：{}",aBoolean);
        }
    }
}
